package com.bgi.cg.oss4j.jfinal;

import cn.hutool.core.bean.BeanUtil;
import com.bgi.cg.oss4j.common.factory.BeanFactory;
import com.bgi.cg.oss4j.common.util.StringUtil;
import com.bgi.cg.oss4j.core.factory.OssSupplierFactory;
import com.jfinal.kit.PropKit;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Description 整合JFinal
 * @Author Z.cg
 * @Date 2023/10/7
 * @Version 1.0
 **/
public class Oss4jPlugin implements com.jfinal.plugin.IPlugin {
    private String configFile = "oss4j.properties", configPreFix = "oss.";
    private char symbol = '-';
    private String aliyun = "aliyun.", huawei = "huawei.", minio = "minio.", tencent = "tencent.", qiniu = "qiniu.", upyun = "upyun.";

    public Oss4jPlugin() {
        super();
    }

    public Oss4jPlugin(String configFile) {
        super();
        this.configFile = configFile;
    }

    public Oss4jPlugin(String configFile, String configPreFix) {
        super();
        this.configFile = configFile;
        this.configPreFix = configPreFix;
    }

    @Override
    public boolean start() {
        //读取配置文件
        Properties properties = PropKit.use(configFile).getProperties();
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix), BeanFactory.getOssConfig(), true, true);
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix + aliyun), OssSupplierFactory.getAliyunConfig(), true, true);
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix + huawei), OssSupplierFactory.getHuaweConig(), true, true);
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix + minio), OssSupplierFactory.getMinioConfig(), true, true);
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix + tencent), OssSupplierFactory.getTencentConfig(), true, true);
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix + qiniu), OssSupplierFactory.getQiniuConfig(), true, true);
        BeanUtil.fillBeanWithMap(removePrefix(properties, configPreFix + upyun), OssSupplierFactory.getUpyunConfig(), true, true);
        return true;
    }

    /**
     * 移除配置前缀
     */
    private Map removePrefix(Properties properties, String fullPreFix) {
        Map<String, Object> map = new HashMap<>();
        properties.forEach((k, v) -> {
            String x0 = k.toString();
            if (x0.startsWith(fullPreFix)) {
                x0 = x0.substring(fullPreFix.length());
                if (!x0.contains(".")) {
                    map.put(StringUtil.toCamelCase(x0, symbol, true), properties.get(k));
                }
            }
        });
        return map;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
